<template>
 <div class="userRegister">
   <div class="from-title">
     <h1>GX-GAMES</h1>
   </div>
   <div class="user-from">
     <el-form label-position="right" :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
       <el-form-item label="用户名:" prop="username">
         <el-input type="text" placeholder="用户名不得大于16个字符，不能含有特殊字符" v-model="ruleForm.username" autocomplete="off"></el-input>
       </el-form-item>
       <el-form-item label="密码:" prop="password">
         <el-input placeholder="请设置您的密码" type="password" v-model="ruleForm.password" autocomplete="off"></el-input>
       </el-form-item>
       <el-form-item label="请确认密码:" prop="checkPass">
         <el-input placeholder="确认您的密码" type="password" v-model="ruleForm.checkPass" autocomplete="off"></el-input>
       </el-form-item>
       <el-form-item label="姓名:" prop="rname">
         <el-input placeholder="请输入您的真实姓名" type="rname" v-model="ruleForm.rname" autocomplete="off"></el-input>
       </el-form-item>
       <el-form-item label="学校:" prop="school">
<!--         <el-input type="school" v-model="ruleForm.school" autocomplete="off"></el-input>-->

         <el-autocomplete
             v-model="ruleForm.school"
             :fetch-suggestions="querySearchAsync"
             placeholder="请输入您的学校名称"
             @select="handleSelect"
             style="width: 100%"
         ></el-autocomplete>

       </el-form-item>
       <el-form-item label="身份:" prop="level">
         <el-select v-model="ruleForm.level" placeholder="请选择你的身份" style="width: 100%">
           <el-option label="学生" value="1"></el-option>
           <el-option label="老师" value="2"></el-option>
         </el-select>
       </el-form-item>
       <el-form-item label="专业:" prop="sex">
<!--         <el-input type="profession" v-model="ruleForm.profession" autocomplete="off"></el-input>-->
         <el-autocomplete
             v-model="ruleForm.sex"
             :fetch-suggestions="querySearchAsync2"
             placeholder="请输入您的专业"
             @select="handleSelect2"
             style="width: 100%"
         ></el-autocomplete>
       </el-form-item>
       <el-form-item label="电话:" prop="phone">
         <el-input placeholder="请输入您的电话" type="phone" v-model="ruleForm.phone" autocomplete="off"></el-input>
       </el-form-item>
       <el-form-item label="邮箱:" prop="email">
         <el-input placeholder="请输入您的邮箱地址" v-model="ruleForm.email"></el-input>
       </el-form-item>
       <el-form-item>
         <el-button class="form-bottom" type="primary" @click="submitForm('ruleForm')">提交</el-button>
       </el-form-item>
       <el-form-item>
         <el-button class="form-bottom" type="success" @click="back">返回登陆</el-button>
       </el-form-item>
       <el-form-item>
         <el-button class="form-bottom" @click="resetForm('ruleForm')">重置</el-button>
       </el-form-item>
     </el-form>
   </div>
 </div>
</template>

<script>
export default {
  name: "register",
  data() {

    //用户名表单验证
    const Username = (rule, value, callback) => {
      const pattern = new RegExp("[`~!@#$^&*()=|{}':;',\\[\\].<>《》/?~！@#￥……&*（）——|{}【】‘；：”“'。，、？]");
      // if (!value) {
      //   return callback(new Error('用户名不能为空'));
      // } else
      if (pattern.test(value)) {
        return callback( new Error('用户名不能包含特殊字符'))
      } else if (value.length>=16) {
        return  callback( new Error('用户名不能大于16个字符'))
      }
      callback()
    };
    //用户名表单验证

    //密码验证
    const validatePass = (rule, value, callback) => {
      // if (value === '') {
      //   callback(new Error('请输入密码'));
      // } else {
        if (this.ruleForm.checkPass !== '') {
          this.$refs.ruleForm.validateField('checkPass');
        }
        callback();
      // }
    };
    const validatePass2 = (rule, value, callback) => {
      // if (value === '') {
      //   callback(new Error('请再次输入密码'));
      // } else
       if (value !== this.ruleForm.password) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    };
    //密码验证
    // 等级
    // const validateLevel =  (rule, value, callback) => {
    //   console.log('等级');
    //   console.log('等级',value);
    //   callback();
    // }

    //手机号验证
    const phoneValidator = (rule, value, callback) => {
      const regMobile = /^1[3|4|5|7|8]\d{9}$/;
      if (!regMobile.test(value)) {
        return callback(new Error('手机号格式错误'));
      }
      callback();
    }
    //手机号验证
    return {

      //远程搜索
      restaurants: [],
      restaurants2: [],
      // timeout:  null,
      //远程搜索

      ruleForm: {
        username:'',
        password: '',
        checkPass: '',
        email: '',
        rname: '',
        level: '',
        school: '',
        sex: '', // 专业，不要问我为什么，文后端
        phone: ''
      },
      rules: {
        username:[
          {required: true, message: '请输入您的用户名', trigger: 'blur'},
          {validator: Username, trigger: 'blur'}
        ],
        password: [
          {required: true, message: '请输入密码', trigger: 'blur'},
          { validator: validatePass, trigger: 'blur' }
        ],
        checkPass: [
          {required: true, message: '请再次输入密码', trigger: 'blur'},
          { validator: validatePass2, trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入您的邮箱地址', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
        ],
        level:[
          { required: true, message: '请选择您的身份', trigger: 'blur' },
          // { validator: validateLevel, trigger: ['blur','change'] }
        ],
        rname:[{required: true, message: '请输入您的姓名', trigger: 'blur'}],
        school: [{required: true, message: '请输入您的学校', trigger: ['blur','change']}],
        sex:[{required: true, message: '请输入您的专业', trigger: ['blur','change']}],
        phone: [
          {required: true,message: '请填写您的手机号', trigger: 'blur'},
          { validator: phoneValidator, trigger: 'blur'}
        ]
      }
    };
  },
  mounted() {
    // 远程搜索
    this.restaurants = this.loadAll();
    this.restaurants2 = this.loadAll2();
    // 远程搜索
  },
  methods: {
    //  远程搜索
    loadAll() {
      return [
        { "value": "重庆移通学院"},{ "value": "重庆文理学院"},{ "value": "重庆邮电大学"},{ "value": "西南政法大学"},
        { "value": "重庆大学"},{ "value": "重庆交通大学"},{ "value": "重庆城市科技学院"},{ "value": "重庆第三军医大学"},
        { "value": "重庆涉外商贸学院"},{ "value": "重庆电子科技学院"},{ "value": "重庆警察学院"},{ "value": "重庆第二师范学院"},
      ];
    },
    loadAll2() {
      return [
        { "value": "软件工程"},{ "value": "土木工程"},{ "value": "计算机科学与技术"},{ "value": "数字媒体与艺术"},
        { "value": "临床医学"},{ "value": "大数据科学"},{ "value": "通信工程"},{ "value": "英语"},
        { "value": "动画传媒"}
      ];
    },
    querySearchAsync(queryString, cb) {
      let restaurants = this.restaurants;
      let results = queryString ? restaurants.filter(this.createStateFilter(queryString)) : restaurants;

      // clearTimeout(this.timeout);
      // this.timeout = setTimeout(() => {
        cb(results);
      // });
    },
    querySearchAsync2(queryString, cb) {
      let restaurants = this.restaurants2;
      let results = queryString ? restaurants.filter(this.createStateFilter(queryString)) : restaurants;

      // clearTimeout(this.timeout);
      // this.timeout = setTimeout(() => {
      cb(results);
      // });
    },
    createStateFilter(queryString) {
      return (state) => {
        return (state.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
      };
    },
    handleSelect(item) {
      item === '1';
    },
    handleSelect2(item) {
      item === '1';
    },
//  远程搜索


    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) { //this.ruleForm
          this.$api.register(this.ruleForm)
            .then(res=>{
              if(res.success){
                this.$alert('前往登陆。', '注册成功！', {
                  confirmButtonText: '确定',
                  callback: () => {
                    this.$router.push('/login');
                    this.$message.success("注册成功！");
                  }
                });
              }
            })
            .catch(err => {
              console.log(err);
            })
        } else {
          this.$alert('系统繁忙，请重试', '注册失败！', {
            confirmButtonText: '确定',
            callback: () => {
              this.$message.warning("注册失败！");
            }
          });
          return false;
        }
      });
    },
    back(){
      this.$router.push('/login')
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    }
  },


}
</script>

<style lang="less" scoped>
.from-title{
  width: 500px;
  margin: 0 auto;
  text-align: center;
  font-size: 20px;
}
.user-from{
  width: 500px;
  margin: 0 auto;
  .demo-ruleForm{
    .form-bottom{
      width: 400px;
    }
  }
}
</style>
